package com.app.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.app.common.Result;
import com.app.mapper.OrderMapper;
import com.app.model.*;
import com.app.service.ActivityService;
import com.app.service.BusinessActivityService;
import com.app.service.BusinessService;
import com.app.service.UserService;
import com.app.utils.CommonHelp;
import com.app.utils.TokenUtils;
import com.app.vo.ActivityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static cn.hutool.crypto.digest.DigestUtil.md5Hex;

/**
 * 活动
 *
 * @author 16693103420
 * @since 2024-01-22
 */
@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    @Autowired
    private BusinessService businessService;
    @Autowired
    private BusinessActivityService businessActivityService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderMapper orderMapper;

    //管理后台查询活动列表
    @GetMapping("/getActivityList")
    public Result getActivityList(@RequestParam(defaultValue = "0") Integer page,
                                  @RequestParam(defaultValue = "10") Integer limit) {
        ActivityVo activityList = activityService.getActivityList(page, limit);
        return Result.success(activityList);
    }

    //查询此商家待添加活动
    @GetMapping("/getActivityByBusiness")
    public Result getActivityByBusiness(@RequestParam(defaultValue = "0") Integer page,
                                        @RequestParam(defaultValue = "10") Integer limit,
                                        Integer businessId) {
        ActivityVo activityList = activityService.getActivityByBusiness(page, limit, businessId);
        return Result.success(activityList);
    }

    //详情
    @GetMapping("/getActivityById")
    public Result getActivityById(Integer id, Double longitude, Double latitude) {
        ActivityModel activity = activityService.getActivityById(id, longitude, latitude);
        return Result.success(activity);
    }

    //立即抢购
    @PostMapping("/buyNowActivity")
    public Result buyNowActivity(@RequestBody ActivityModel activityModel, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String openId = TokenUtils.verify(token);
        UserModel user = userService.getUserByOpenid(openId);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        ActivityModel activity = activityService.getById(activityModel.getId());
        if(activity == null)
        {
            return Result.error(201, "活动不存在");
        }
        BusinessModel businessModel=this.businessService.getById(activity.getBusinessId());

        if ( 1 != activity.getClassification()){
            if (activityModel.getPassword() == null) {
                return Result.error(405, "请输入支付密码");
            }
            String newWord = md5Hex(activityModel.getPassword() + user.getSalt());
            if (!user.getPaymentPassword().equals(newWord)) {
                return Result.error(201, "支付密码错误");
            }
        }

        if(businessModel == null)
        {
            return Result.error(201, "商家不存在");
        }
        if(businessModel.getUserPhone().equals(user.getPhone()))
        {
            return Result.error(201, "不可购买自己的商品");
        }

        if (activity.getNumber() <= 0) {
            return Result.error(201, "活动库存不足");
        }
        if ( 1 != activity.getClassification()){
            if (user.getVoucher() < activity.getPrice()) {
                return Result.error(201, "益联券不足");
            }
        }
        //每个ID账号，每天在限时免费板块只能领取一样产品
        QueryWrapper<OrderModel> qw = new QueryWrapper<>();
        qw.eq("user_id", user.getId());
        qw.apply("DATE(create_time) = CURDATE() ");
        OrderModel model = orderMapper.selectOne(qw);
        if (null != model){
            return Result.error(201, "每个ID账号每天只能领取一样产品");
        }

        activityService.buyNowActivity(activity, user);
        return Result.success("抢购成功");
    }

    //新增和修改
    @PostMapping("/addAndUpdateActivity")
    public Result addAndUpdateActivity(@RequestBody ActivityModel activityModel) {
        ActivityModel activity = activityService.getById(activityModel.getId());
        if (activity != null) {
            activityModel.setUpdateTime(CommonHelp.getNowTimestamp());
            activityService.updateById(activityModel);
            return Result.success("修改成功");
        } else {
            activityModel.setCreateTime(CommonHelp.getNowTimestamp());
            activityService.save(activityModel);
            return Result.success("添加成功");
        }
    }

    //删除
    @GetMapping("/delActivity")
    public Result delActivity(Integer id) {
        QueryWrapper<BusinessActivityModel> qw = new QueryWrapper<>();
        qw.eq("activity_id", id);
        List<BusinessActivityModel> list = businessActivityService.list(qw);
        if (CollectionUtil.isNotEmpty(list)) {
            return Result.error(201, "此活动正被商家使用,请勿删除");
        }
        activityService.removeById(id);
        return Result.success("删除成功");
    }

    /**
     * 获取活动详细信息
     *
     * @param id id
     * @return {@link Result}
     */
    @GetMapping("/getActivityDetail")
    public Result getActivityDetail(Integer id) {
        return Result.success(activityService.getById(id));
    }
}

